from datastore.resource import *
from datastore.uri import *
from runtime.service import *

# testing
import hashlib
import base64


class MediaService(Service):
    def cb_start(self, uri, action, res):
        # we want to handle requests for each of these media types
        self.spaces.set_process(res.options.js, self.cb_load)
        self.spaces.set_process(res.options.css, self.cb_load)
        self.spaces.set_process(res.options.jpg, self.cb_load)
        
        # see http://antifavicon.com/
        self.spaces.set_process(res.options.favicon, self.cb_load)

        self.spaces.set_process(res.options.pdf,self.cb_load_pdf)

    def cb_load(self, uri, action, res):
        # this gets the resource twice, once for exists and once for the get. 
        # might want to cache in the future.
        
        # special case
        if uri == Uri('external:favicon.ico'):
            uri = Uri('external:images/base/favicon.ico')
        
        self.logger.log(logging.INFO, "%s (%s)", action, uri)
        
        if action == 'exists':
            try:
                resources = self.datastore.find(
                    [(Uri('term:base/runtime/file/file_uri'), uri)])
                self.logger.log(logging.DEBUG, "Media Exists!")
                return True
            except:
                self.logger.log(logging.DEBUG, "Media not found! %s", uri)
                return False
        elif action == 'get':
            resources = self.datastore.find(
                [(Uri('term:base/runtime/file/file_uri'), uri)])
            media_res = resources[0]
            # change its type to one http_service will return as is.
            media_res.set_type(Uri('term:base/services/http/response'))
            # and set the correct content type variable
            media_res.content_type = media_res.content_mime_type
            media_res.status = 200
            return media_res
            
    def cb_load_pdf(self, uri, action, res):
       
        if action == 'exists' :
            return True
        elif action == 'get' :
            parts = uri.split()
            doc_id = parts[-1]
                     
            try :
                resources = self.datastore.find([(Uri('documentId'),doc_id)])
            except NotFoundException :
                content = 'We were unable to find the resource you requested.'
                response = Resource(type='term:base/services/http/response')
                response.set_var('content_type','text/plain')
                response.set_var('status',404)
                response.set_var('content', content)
                response.set_var('content_length', len(content))
                return response
            
            resource = resources[0]   
            pdf_res = Resource(type=('term:base/services/http/response'))
            pdf_res.set_var('status',200)
            
            content = base64.standard_b64decode(resource.get_var('pdf'))
            
            pdf_res.set_var('content',content)
            pdf_res.set_var('content_type','application/pdf')
            pdf_res.set_var('content_length',len(content))
          
            return pdf_res
        
        
